import tkinter as tk
from tkinter import ttk
import tkinter.messagebox
import os
import sys
import time
from tts_ws_python3_demo import text2wav
from playsound import playsound


class TtsPlay:
    def __init__(self):
        self.vcn = 'xiaoyan'
        self.APP_ID = 'xxx' # 请填上自己的appid
        self.API_KEY = 'xxx' # 请填上自己的apikey
        self.SECRET_KEY = 'xxx' # 请填上自己的apisecret

        self.fname = ""

        self.root = tk.Tk()  # 初始化窗口
        self.root.title("语音合成系统")  # 窗口名称
        self.root.geometry("600x550")  # 设置窗口大小
        self.root.resizable(0, 0)   # 为了方便固定窗口大小
        self.tk_lb = tk.Label(self.root, text='请选择语音发音人')  # 标签
        self.tk_text = tk.Text(self.root, width=77, height=30)  # 多行文本框
        self.tk_cb_vcn = ttk.Combobox(self.root, width=12)  # 下拉列表框
        # 设置下拉列表框的内容
        self.tk_cb_vcn['values'] = ("甜美女声-小燕", "亲切男声-许久", "知性女声-小萍", "可爱童声-许小宝", "亲切女声-小婧")
        self.tk_cb_vcn.current(0)  # 将当前选择状态置为0,也就是第一项
        self.tk_cb_vcn.bind("<<ComboboxSelected>>", self.select_vcn)
        self.tk_tts_file = tk.Label(self.root, text='生成文件名')
        self.b1 = tk.Button(self.root, text='进行语音合成', width=10, height=1, command=self.xfyun_tts)  # 按钮
        self.tk_play = tk.Button(self.root, text='播放', width=10, height=1, command=self.play_sound)  # 按钮
        # 各个组件的位置
        self.tk_tts_file.place(x=30, y=500)
        self.b1.place(x=300, y=500)
        self.tk_play.place(x=400, y=500)
        self.tk_lb.place(x=30, y=30)
        self.tk_cb_vcn.place(x=154, y=30)

        self.tk_text.place(x=30, y=60)
        self.root.mainloop()

    def select_vcn(self, *args):
        if self.tk_cb_vcn.get() == '甜美女声-小燕':
            self.vcn = "xiaoyan"
        elif self.tk_cb_vcn.get() == '亲切男声-许久':
            self.vcn = "aisjiuxu"
        elif self.tk_cb_vcn.get() == '知性女声-小萍':
            self.vcn = "aisxping"
        elif self.tk_cb_vcn.get() == '可爱童声-许小宝':
            self.vcn = "aisbabyxu"
        elif self.tk_cb_vcn.get() == '亲切女声-小婧':
            self.vcn = "aisjinger"

    def xfyun_tts(self):
        tts_text = self.tk_text.get('0.0', 'end')  # 获取文本内容
        # 前后的空格以及换行符
        tts_text = tts_text.strip('\r\n')
        tts_text = tts_text.strip('\n')
        tts_text = tts_text.strip(' ')

        if not tts_text:
            tkinter.messagebox.showinfo("提示", "请输入文本内容")
            return

        fname = time.strftime("%Y%m%d%H%M%S", time.localtime())
        self.fname = os.path.dirname(sys.argv[0]) + "/" + fname + ".wav"
        # print(self.fname)
        self.tk_tts_file["text"] = self.fname
        text2wav(self.APP_ID, self.SECRET_KEY, self.API_KEY, tts_text, self.vcn, self.fname)

    def play_sound(self):
        playsound(self.fname)


if __name__ == "__main__":
    TtsPlay()
